package com.ys.erp.stage_user_service.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ys.erp.common.constant.CatOrderConstant;
import com.ys.erp.common.enums.EnableEnum;
import com.ys.erp.common.enums.RedisKey;
import com.ys.erp.common.enums.old.StatusOldEnum;
import com.ys.erp.common.util.DateUtil;
import com.ys.erp.common.util.MoneyUtil;
import com.ys.erp.entity.data.bean.*;
import com.ys.erp.entity.service.*;
import com.ys.erp.framework.annotation.RedissonLock;
import com.ys.erp.framework.bean.dto.StageEmpDTO;
import com.ys.erp.framework.exception.YsException;
import com.ys.erp.framework.response.AbstractResponseCode;
import com.ys.erp.framework.response.PageDTO;
import com.ys.erp.stage_user_service.bean.condition.UserCatCondition;
import com.ys.erp.stage_user_service.bean.vo.UserVO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 南山
 * @date 2025/07/05 14:41
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserCatService {
    private final IUserCatService iUserCatService;
    private final RedissonClient redisson;
    private final IShopService iShopService;
    private final ICatService iCatService;
    private final IUserService iUserService;
    private final IEmployeeService iEmployeeService;
    private final ICatExtService iCatExtService;
    private final IUserCatExtService iUserCatExtService;
    private final ICatCageService iCatCageService;

    private final IUserCatRecordService iUserCatRecordService;
   /* private final DingDingUtil dingDingUtil;

    @Transactional(rollbackFor = Exception.class)
    @RedissonLock(key = "#con.catId")
    public void addUserCat(StageEmpDTO emp, UserCatCondition.AddUserCatCon con) {
        RLock lock = redisson.getLock(MessageFormat.format(RedisKey.Enums.USER_ADD_CAT.getKey(), con.getUserId()));
        boolean lockFlag = false;
        try {
            lockFlag = lock.tryLock();
            if (!lockFlag) {
                return;
            }
            //查询店铺
            Shop shop = iShopService.getByCode(con.getShopCode());
            if (ObjectUtil.isEmpty(shop)) {
                return;
            }
            //查询猫咪状态
            Cat cat = iCatService.getById(con.getCatId());
            if (ObjectUtil.isEmpty(cat)) {
                return;
            }
            if (cat.getCatStatus() != StatusOldEnum.CATS_SALE.getStatus()) {
                throw new YsException(-1, "这个猫咪已被领走，请登录小程序刷新查看");
            }
            User user = iUserService.getById(con.getUserId());
            if (ObjectUtil.isEmpty(user)) {
                log.info("用户不存在");
                return;
            }
            QueryWrapper<UserCat> userCatQw = new QueryWrapper<>();
            userCatQw.lambda().eq(UserCat::getUserId, con.getUserId())
                    .eq(UserCat::getCatCode, cat.getCatCode());
            UserCat userCat = iUserCatService.getOne(userCatQw);
            if (ObjectUtil.isEmpty(userCat)) {
                userCat = new UserCat();
            }
            if (cat.getCatStatus() != StatusOldEnum.CATS_SALE.getStatus()) {
                throw new YsException(AbstractResponseCode.VALID_ERROR);
            }
            if (!con.getChannelEmpIds().isEmpty()) {
                QueryWrapper<Employee> empQw = new QueryWrapper<>();
                empQw.lambda().select(Employee::getId)
                        .in(Employee::getId, con.getChannelEmpIds());
                List<String> channelEmpIds = iEmployeeService.listObjs(empQw, String::valueOf);
                if (!channelEmpIds.isEmpty()) {
                    userCat.setChannelEmpIds(String.join(",", channelEmpIds));
                }
            }
            userCat.setUserId(user.getId());
            userCat.setCatId(cat.getId());
            userCat.setCatCode(cat.getCatCode());
            userCat.setCatPhoto(cat.getPhotos());
            userCat.setCatNickName(cat.getNickName());
            userCat.setMaintainPhone(con.getMaintainPhone());
            userCat.setChannelSource(con.getChannelSourceType());
            userCat.setShopCode(shop.getShopCode());
            userCat.setShopName(shop.getName());
            userCat.setCatMoney(0L);
            userCat.setContractType(con.getContractType());
            if (Objects.nonNull(con.getContractType())) {
                switch (con.getContractType()) {
                    case 0:
                        userCat.setMaintainMethod("芝麻分签约");
                        userCat.setUserFeeRemark(con.getPeriodMoney() + "元*" + con.getCatPeriod() + "期");
                        break;
                    case 1:
                        userCat.setMaintainMethod("直接购买");
                        userCat.setFullMoney(MoneyUtil.str2Long(con.getFullMoney()));
                        userCat.setUserFeeRemark(null);
                        break;
                    case 2:
                        userCat.setMaintainMethod("全款充值");
                        userCat.setFullMoney(MoneyUtil.str2Long(con.getFullMoney()));
                        userCat.setUserFeeRemark(null);
                        break;
                    case 3:
                        userCat.setMaintainMethod("小偿无忧");
                        userCat.setUserFeeRemark(con.getPeriodMoney() + "元*" + con.getCatPeriod() + "期");
                        userCat.setConserveServiceFee(MoneyUtil.str2Long(con.getConserveServiceFee()));
                        break;
                }
            }
            String describe = "";
            String ddMes = "";
            UpdateWrapper<Cat> catUw = new UpdateWrapper<>();
            catUw.lambda().eq(Cat::getId, cat.getId());
            if (con.getIsPre() == EnableEnum.YES.getEnable()) {
                //是预定
                describe = "预定猫咪";
                userCat.setCatStatus(StatusOldEnum.USER_CAT_PREDETERMINE.getStatus());
                cat.setCatStatus(StatusOldEnum.CATS_AD.getStatus());
                catUw.lambda().set(Cat::getCatStatus, StatusOldEnum.CATS_AD.getStatus());
                iCatService.update(catUw);
                ddMes = MessageFormat.format(CatOrderConstant.PRE_CAT, userCat.getUserId().toString(), cat.getCatCode(), con.getPredictMoney());
            } else {
                //增加猫咪售卖次数以及更新售卖天数
                UpdateWrapper<CatExt> catExtUw = new UpdateWrapper<>();
                catExtUw.lambda().eq(CatExt::getCatCode, cat.getCatCode());
                catExtUw.lambda().set(CatExt::getSalesDays,
                        Integer.valueOf(DateUtil.calcDifferDay(Objects.isNull(cat.getToShopTime())
                                        ? cat.getCreateTime() : cat.getToShopTime(),
                                LocalDateTime.now()).toString()));
                catExtUw.setSql("sales_num = sales_num + 1");
                iCatExtService.update(catExtUw);
                //更新猫咪
                describe = "无预定，领走猫咪";
                userCat.setCatStatus(StatusOldEnum.USER_CAT_TAKE.getStatus());
                userCat.setTakeDate(DateUtil.stringToLocalDateTime(con.getTakeDate()));
//            userCat.setTakeDate(LocalDateTime.now());
                cat.setCatStatus(StatusOldEnum.CATS_SOLD.getStatus());
                catUw.lambda().set(Cat::getCatStatus, StatusOldEnum.CATS_SOLD.getStatus());
                iCatService.update(catUw);
                ddMes = MessageFormat.format(CatOrderConstant.TAKE_CAT, userCat.getUserId().toString(), cat.getCatCode());
            }
            userCat.setFullMoney(MoneyUtil.str2Long(con.getFullMoney()));
            userCat.setIsDisable(EnableEnum.NO.getEnable());
            userCat.setIsFreeze(EnableEnum.NO.getEnable());
            log.info("绑定猫咪成功");
            iUserCatService.saveOrUpdate(userCat);
            QueryWrapper<UserCatExt> userCatExtQw = new QueryWrapper<>();
            userCatExtQw.lambda().eq(UserCatExt::getUserId, con.getUserId())
                    .eq(UserCatExt::getCatCode, cat.getCatCode());
            UserCatExt userCatExt = iUserCatExtService.getOne(userCatExtQw);
            boolean saveExtFlag = false;
            if (ObjectUtil.isEmpty(userCatExt)) {
                saveExtFlag = true;
                userCatExt = new UserCatExt();
            }
            userCatExt.setId(userCat.getId());
            if (con.getIsPre() == EnableEnum.YES.getEnable()) {
                userCatExt.setPreDate(LocalDateTime.now());
                userCatExt.setPredictMoney(MoneyUtil.str2Long(con.getPredictMoney()));
            }
            userCatExt.setUserId(userCat.getUserId());
            userCatExt.setPredictDate(DateUtil.stringToLocalDate(con.getPreDateTime()));
            userCatExt.setCatCode(userCat.getCatCode());
            userCatExt.setSignShop(con.getSignShop());
            userCatExt.setIsEmpTake(con.getIsEmpTake());
            userCatExt.setTakeEmpId(con.getTakeEmpId());
            userCatExt.setCatPeriod(con.getCatPeriod());
            userCatExt.setPeriodMoney(MoneyUtil.str2Long(con.getPeriodMoney()));
            userCatExt.setBuyRemark(con.getBuyRemark());
            userCatExt.setContractSignWayType(con.getContractSignWayType());
            userCatExt.setShopCode(userCat.getShopCode());
            userCatExt.setIsSignContract(con.getIsSignContract());
            userCatExt.setSignContractType(con.getSignContractType());
            userCatExt.setGuideEmpId(con.getGuideEmpId());
            userCatExt.setSignEmpId(con.getSignEmpId());
            userCatExt.setRemark(con.getRemark());
            userCatExt.setLastTakeDate(LocalDate.now());
            userCatExt.setPreReason(con.getPreReason());
            userCatExt.setCheckEmpId(con.getCheckEmpId());
            if (con.getIsPre() == EnableEnum.NO.getEnable() && ObjectUtil.isNotEmpty(cat.getCatCageId())) {
                //领走设置猫笼
                CatCage catCage = iCatCageService.getById(cat.getCatCageId());
                if (ObjectUtil.isNotEmpty(catCage)) {
                    userCatExt.setCageArea(catCage.getCageArea());
                    userCatExt.setCatUnit(catCage.getCatUnit());
                    userCatExt.setCageStorey(catCage.getCageStorey());
                    userCatExt.setCageType(catCage.getCageType());
                    userCatExt.setCageNo(catCage.getCageNo());
                    //更新猫笼
                    List<String> strings = JSONArray.parseArray(catCage.getCatCode(), String.class);
                    strings.removeIf(it -> cat.getCatCode().equals(it));
                    catCage.setCatCode(JSONArray.toJSONString(strings));
                    iCatCageService.updateById(catCage);
                }
            }
            if (saveExtFlag) {
                iUserCatExtService.save(userCatExt);
            } else {
                iUserCatExtService.updateById(userCatExt);
            }
            //增加记录日志
            UserCatRecord userCatRecord = new UserCatRecord();
            userCatRecord.setUserId(userCat.getUserId());
            userCatRecord.setCatCode(userCat.getCatCode());
            userCatRecord.setRecordDescribe(describe);
            userCatRecord.setRecordTime(LocalDateTime.now());
            userCatRecord.setEmpId(emp.getId());
            userCatRecord.setEmpName(emp.getRealName());
            userCatRecord.setIsHaveInMoney(con.getIsHaveInMoney());
            userCatRecord.setInMoneyDate(DateUtil.stringToLocalDate(con.getInMoneyDate()));
            if (con.getIsHaveInMoney() == EnableEnum.YES.getEnable()) {
                userCatRecord.setInMoneyDetail(JSONObject.toJSONString(con.getInMoneyDetail()));
            } else {
                userCatRecord.setInMoneyDetail("[]");
            }
            if (con.getIsHaveInMoney() == EnableEnum.YES.getEnable()) {
                long sum = con.getInMoneyDetail().stream()
                        .mapToLong(it -> MoneyUtil.str2Long(it.getMoney()))
                        .sum();
                userCatRecord.setInMoneyTotal(sum);
            } else {
                userCatRecord.setInMoneyTotal(0L);
            }
            iUserCatRecordService.save(userCatRecord);
            if (CollectionUtils.isNotEmpty(con.getContractInfoIds())) {
                bindContractInfo(con.getContractInfoIds(), userCat.getUserId());
            }
            //增加日志
            iEventLogService.insertEvent(emp, "新增" + user.getId() + "猫咪钱包：" + cat.getCatCode(), userCat.getId(), EnableEnum.NO.getEnable(), JSONObject.toJSONString(con));
            if (con.getIsHaveInMoney() == EnableEnum.YES.getEnable()) {
                ddMes += ",收款：" + MoneyUtil.long2Str(userCatRecord.getInMoneyTotal());
                dingDingUtil.sendToAfterSaleAndFinance(ddMes);
            } else {
                dingDingUtil.sendToAfterSale(ddMes);
            }
            //发放卡券
            QueryWrapper<CardCoupon> cardCouponQw = new QueryWrapper<>();
            cardCouponQw.lambda().eq(CardCoupon::getIsNewCatGet, EnableEnum.YES.getEnable());
            List<CardCoupon> cardCouponList = iCardCouponService.list(cardCouponQw);
            List<UserCardCoupon> saveUserCardList = new ArrayList<>();
            LocalDate nowDate = LocalDate.now();
            for (CardCoupon coupon : cardCouponList) {
                UserCardCoupon userCardCoupon = new UserCardCoupon();
                userCardCoupon.setUserId(userCat.getUserId());
                userCardCoupon.setCatCode(userCat.getCatCode());
                userCardCoupon.setCardCouponName(coupon.getName());
                userCardCoupon.setCardCouponId(coupon.getId());
                userCardCoupon.setCardCouponPic(coupon.getPic());
                userCardCoupon.setTotalQuantity(coupon.getNewCatQuantity());
                userCardCoupon.setUsedQuantity(0);
                userCardCoupon.setGetTime(nowDate);
                userCardCoupon.setEndTime(nowDate.plusDays(coupon.getCanUseDay()));
                saveUserCardList.add(userCardCoupon);
            }
            iUserCardCouponService.saveBatch(saveUserCardList);
            if (con.getIsPre() == EnableEnum.YES.getEnable()) {
                wxYsSendMessageUtil.sendTakeCat(
                        user.getNickName(),
                        shop.getName(),
                        shop.getShopCode(),
                        userCat.getCatCode(),
                        StatusEnum.USER_CAT_PREDETERMINE.getRemark(),
                        null
                );
            } else {
                wxYsSendMessageUtil.sendTakeCat(
                        user.getNickName(),
                        shop.getName(),
                        shop.getShopCode(),
                        userCat.getCatCode(),
                        StatusEnum.USER_CAT_TAKE.getRemark(),
                        "已领走（" + MoneyUtil.long2Str(userCatExt.getPeriodMoney()) + "*" + userCatExt.getCatPeriod() + "期）"
                );
            }
            eventPublisher.publishEvent(new TakePetEvent(userCat.getUserId(), userCat.getCatCode()));
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
*/

    public PageDTO<UserVO> addContract(StageEmpDTO empDto, UserCatCondition.UserCatContractAddCon con) {
        return null;
    }
}
